﻿using AuApmt.Models.Db.Context;
using AuApmt.Models.DbModels;
using AuApmt.Models.Dto;

namespace AuApmt.Repos.Schedules
{
    public class SubjectRepo(
        DataContext context)
        : Repo<Subject>(context)
    {
        public List<SubjectDto> IndexSubject()
        {
            return Existing
                .OrderBy(x => x.Name)
                .Select(x => new SubjectDto()
                {
                    Id = x.Id,
                    Name = x.Name,
                    Intro = x.Intro,
                    SlotsDefault = x.SlotsDefault,
                    Difficulty = x.Difficulty,
                    CategoryId = x.CategoryId
                }).ToList();
        }
        public bool CreateSubject(SubjectDto s, out string? errmsg)
        {
            errmsg = CheckModel(s.Name, s.Intro);
            if (errmsg is { })
                return false;
            Subject newSubject = new()
            {
                Name = s.Name,
                Intro = s.Intro,
                SlotsDefault = s.SlotsDefault,
                Difficulty = s.Difficulty,
                CategoryId = s.CategoryId
            };
            base.Add(newSubject);
            return true;
        }

        public bool UpdateSubject(SubjectDto s, out string? errmsg)
        {
            errmsg = CheckModel(s.Name, s.Intro, s.Id);
            if (errmsg is { })
                return false;
            var subject = base.Get(s.Id);
            if(subject is null)
            {
                errmsg = "找不到指定科目";
                return false;
            }
            subject.Name = s.Name;
            subject.Intro = s.Intro;
            subject.SlotsDefault = s.SlotsDefault;
            subject.Difficulty = s.Difficulty;
            subject.CategoryId = s.CategoryId;
            base.Update(subject, true);
            return true;
        }

        public bool DeleteSubject(int id, out string? errmsg)
        {
            var subject = base.Get(id);
            if (subject is null)
            {
                errmsg = "找不到指定科目";
                return false;
            }
            base.FakeRemove(subject, true);
            errmsg = null;
            return true;
        }

        private string? CheckModel(
            string? name, string? intro, int id = 0)
        {
            if (name is null || name.Length < 1 || name.Length > 16)
                return "科目名必须在1-16个字符";
            if (intro is { } && intro.Length > 256)
                return "简介不能超过256字符";
            if (Existing.Any(x => x.Name == name && x.Id != id))
                return "该名称已经被占用";
            return null;
        }
    }
}
